package net.tbao.cart.controller;

import net.tbao.cart.interceptro.CartInterceptro;
import net.tbao.cart.service.CartSevice;
import net.tbao.cart.vo.Cart;
import net.tbao.cart.vo.CartItem;
import net.tbao.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;


@Controller
public class CartController {
    @Autowired
    CartSevice cartSevice;

    @GetMapping("/currentUserCartItems")
    @ResponseBody
    public List<CartItem> getCurrentUserCartItems(){
        return cartSevice.getUserCartItems();
    }


    @GetMapping("/delItem")
    public  String delItem(@RequestParam("skuId") Long skuId){
        cartSevice.delItem(skuId);
        return "redirect:http://cart.tbao.cn/cart.html";
    }

    /**
     * 修改购物项数量
     * @param skuId
     * @param num
     * @return
     */
    @GetMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId,@RequestParam("num")Integer num){
        cartSevice.changeItemCount(skuId,num);
        return "redirect:http://cart.tbao.cn/cart.html";
    }

    /**
     * 购物车绑定
     * @param skuId
     * @param check
     * @return
     */
    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId,@RequestParam("check")Integer check){
        cartSevice.checkItem(skuId,check);
        return "redirect:http://cart.tbao.cn/cart.html";
    }

    /**
     *
     * @return
     */
    @GetMapping("/cart.html")
    public String cartListPage(Model model) throws ExecutionException, InterruptedException {
        Cart cart = cartSevice.getCart();
        model.addAttribute("cart", cart);
        return "cartList";
    }
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num")Integer number, RedirectAttributes ra) throws ExecutionException, InterruptedException {

      cartSevice.addToCart(skuId,number);
        ra.addAttribute("skuId",skuId);

        return "redirect:http://cart.tbao.cn/andToCartSussess.html";
    }
    @GetMapping("/andToCartSussess.html")
    public String andToCartSussess(@RequestParam("skuId")Long skuId, Model model){
       CartItem cartItem= cartSevice.getCartItem(skuId);
       model.addAttribute("item",cartItem);
        return "success";
    }
}
